<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Models\Focus;
use App\Models\Notebook;
use App\Models\User;
use App\Services\NotifyService;
use Illuminate\Http\Request;

class FocusController extends BaseController
{

    public $model = Focus::class;

    /**
     * 关注
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     * @throws \Throwable
     */
    public function store(Request $request) {
        $this->validate($request, [
            'target_user_id' => 'required'
        ]);
        $user = $this->getUser();
        $input = $request->input();
        if ($input['target_user_id'] == $user->id)
            return $this->failed("不能对自己操作");

        $input['user_id'] = $user->id;
        $targetModel = User::find($input['target_user_id']);
        if (!$targetModel)
            return $this->failed('target_user_id对应用户不存在');

        $one = (new $this->model)->where('user_id', $user->id)->where('target_user_id', $input['target_user_id'])->first();
        if ($one) {
            $one->delete();
            $star = 'cancel';
            $user->increment('focus_count', -1);
            $targetModel->increment('fans_count', -1);
        } else {
            $this->model::create($input);
            $star = 'ok';
            NotifyService::store($user->id, 2, 0, $input['target_user_id']);
            $user->increment('focus_count', 1);
            $targetModel->increment('fans_count', 1);
        }
        $latest = Notebook::first();
        $latest->updated_at = date('Y-m-d H:i:s');
        $latest->save();

        return $this->success([
            'star' => $star
        ]);
    }

}

